/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.ssau.berlin.jsf.validation;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlSelectOneMenu;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import ru.ssau.berlin.entity.AttributeType;
import ru.ssau.berlin.framework.AttributeTypeEnum;

/**
 *
 * @author Caesar
 */
public class RoleValidator extends AbstactValidator implements Validator {

    private static final String ATTRIBUTE = "role";

    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        AttributeType type = (AttributeType)((HtmlSelectOneMenu)component
                .findComponent(ATTRIBUTE)).getValue();
        AttributeTypeEnum typeEnum = getEnum(type);
        if (value == null) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Null is not legal here",
                    "Null is not legal here"));
        }
        validate(typeEnum, value.toString());
    }

    private AttributeTypeEnum getEnum(AttributeType type) {
        for (AttributeTypeEnum enumType: AttributeTypeEnum.values()) {
            if (type.getName().equalsIgnoreCase(enumType.name())) {
                return enumType;
            }
        }
        throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                "Unexpected attribute type",
                "Unexpected attribute type: " + type));
    }

}
